package com.report.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Base64;

/**
 * @author summer
 * @version 1.0
 * @date 2024/8/11 14:11
 */
public class FileUtils {

    /**
     * file转换为base64
     * 注意：这里转换为base64后，是不包含文件head头的
     */
    public static String fileToBase64(File file) {
        Base64.Encoder base64 = Base64.getEncoder();
        String base64Str = null;
        try (FileInputStream fis = new FileInputStream(file);
             ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            base64Str = base64.encodeToString(bos.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return base64Str;
    }

}
